/************************************
 * Package: RGcpp					*
 * Authors: Rui Eduardo Gouveia Gil	*
 * Date: 2010						*
 ************************************/
#include "rgcpp/net/http/HTTPDownloader.h"
#include <fstream>

namespace rgcpp
{

size_t responseCallback(void* ptr, size_t size, size_t nmemb, void* stream)
{
	std::ofstream* file = (std::ofstream*)stream;
	file->write((char *)ptr,(size*nmemb));
	return (size * nmemb);
}

bool HTTPDownloader::downloadFile(const std::string& url, const std::string& file)
{
	CURL* handler = curl_easy_init();
	if(!handler)
		return false;

	std::ofstream fstream(file.c_str(),std::ios_base::binary | std::ios_base::out | std::ios_base::trunc);
	if(!fstream.good())
		return false;

	curl_easy_setopt(handler,CURLOPT_HTTPGET,1);
	curl_easy_setopt(handler,CURLOPT_NOPROGRESS,0);
	curl_easy_setopt(handler,CURLOPT_WRITEDATA,&fstream);
	curl_easy_setopt(handler,CURLOPT_URL,url.c_str());
	curl_easy_setopt(handler,CURLOPT_CUSTOMREQUEST,NULL);
	curl_easy_setopt(handler,CURLOPT_WRITEFUNCTION,&responseCallback);

	bool result = (curl_easy_perform(handler)==0);

	curl_easy_cleanup(handler);
	fstream.close();

	if(result)
	{
		std::ifstream fcheck(file.c_str(),std::ios_base::binary | std::ios_base::in);
		if(!fcheck.good())
			return false;

		fcheck.seekg(0,std::ios::end);
		unsigned int size=fcheck.tellg();
		fcheck.seekg(0,std::ios::beg);

		if(size<MAX_HTTPDOWNLOADER_SIZE_CHECK)
		{
			std::string line;
			std::string content;

			std::getline(fcheck,line);
			content+=line+"\n";

			if(content[0]=='<')
			{
				while(!fcheck.eof())
				{
					std::getline(fcheck,line);
					content+=line+"\n";
				}

				if(content.find("404")!=std::string::npos)
					result = false;
				else if(content.find(">AccessDenied<")!=std::string::npos)
					result = false;
			}
		}

		fcheck.close();
	}

	if(!result)
		::remove(file.c_str());

	return result;
}

}
